package client

import (
	"context"
	"gitee.com/enjoy_5/cart-rpc/consts"
	proto "gitee.com/enjoy_5/cart-rpc/proto"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)

// 创建grpc客户端连接
func client(ctx context.Context, hand func(c proto.CartClient) error) error {
	service, err := nacos.FindHealthService(consts.SERVICE_NAME, consts.GROUP_NAME)
	if err != nil {
		return err
	}
	conn, err := grpc.NewClient(service, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}
	defer conn.Close()

	// Contact the server and print out its response.
	_, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()

	c := proto.NewCartClient(conn)

	return hand(c)
}

// 添加商品到购物车
func CreateCartGoods(ctx context.Context, in *proto.EnjoyCart) (info *proto.EnjoyCart, err error) {
	err = client(ctx, func(c proto.CartClient) error {
		cart, err := c.CreateCart(ctx, &proto.CreateCartRequest{In: in})
		if err != nil {
			return err
		}

		info = cart.GetInfo()
		return nil
	})
	return
}

// 删除购物车商品
func DeleteCartGoods(ctx context.Context, userId int32, goodsId []int32) (info *proto.EnjoyCart, err error) {
	err = client(ctx, func(c proto.CartClient) error {
		cart, err := c.DeleteCart(ctx, &proto.DeleteCartRequest{
			UserId:  userId,
			GoodsId: goodsId,
		})

		info = cart.GetInfo()
		return err
	})
	return
}

// 修改购物车商品信息
func UpdateCartGoods(ctx context.Context, userId, goodsId, quantity int32) (info *proto.EnjoyCart, err error) {
	err = client(ctx, func(c proto.CartClient) error {
		number, err := c.UpdateCartGoodsNumber(ctx, &proto.UpdateCartGoodsNumberRequest{
			UserId:   userId,
			GoodsId:  goodsId,
			Quantity: quantity,
		})

		info = number.GetInfo()
		return err
	})
	return
}

// 购物车列表
func GetCartListByUserId(ctx context.Context, userId int32) (info []*proto.EnjoyCart, err error) {
	err = client(ctx, func(c proto.CartClient) error {
		cart, err := c.ListCart(ctx, &proto.ListCartRequest{UserId: userId})

		info = cart.GetList()
		return err
	})

	return
}

// 查询购物车详情
func GetCartInfo(ctx context.Context, userId, goodsId int32) (info *proto.EnjoyCart, err error) {
	err = client(ctx, func(c proto.CartClient) error {
		cartInfo, err := c.GetCartInfo(ctx, &proto.GetCartInfoRequest{
			UserId:  userId,
			GoodsId: goodsId,
		})

		info = cartInfo.GetInfo()
		return err
	})
	return
}
